<template>
  <div>
    <el-drawer
      :title="!dataForm.id ? '新增' : '修改'"
      :visible="visible"
      size="800px"
      @close="closeDialog"
      append-to-body
    >

      <div style="margin: 0px 0px 70px 0px">
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          label-width="80px"
          v-loading="loading">
          
          <el-row v-for="(detail, index) in dataForm.details" :key="index" class="border-buttom" style="margin:0px 30px">
            <el-row style="margin-top:20px">
              <el-row v-if="index != 0" style="margin:0px 0px 20px 0px;text-align: right;">
                <el-link :underline="false" type="danger" @click="handleDel(detail)">
                  <span style="font-size:12px">移除</span>
                </el-link>
              </el-row>
              <el-form-item label="类型" :prop="'details.' + index + '.type'"
                :rules="[{ required: true, message: '类型不能为空', trigger: 'blur'}]">
                <el-select
                  v-model="detail.type"
                  filterable
                  placeholder="请选择类型"
                  clearable
                  size="small"
                  class="margin-left-xs"
                  style="width:100%"
                  @change="handleTypeChange(detail)"
                >
                  <el-option
                    v-for="dict in topicDetailTypeList"
                    :key="dict.value"
                    :label="dict.text"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-row>

            <el-row v-if="detail.type == topicDetailTypeEnum.image">
              <el-form-item  label="图片"  :prop="'details.' + index + '.imageUrl'"
                :rules="[{ required: true, message: '图片不能为空', trigger: 'blur'}]">
                <ImageUploadSingle v-model="detail.imageUrl"></ImageUploadSingle>
              </el-form-item>
            </el-row>

            <el-row v-if="detail.type == topicDetailTypeEnum.lottery">
              <el-form-item  label="抽奖"  :prop="'details.' + index + '.lotteryId'"
                :rules="[{ required: true, message: '抽奖不能为空', trigger: 'blur'}]">
                <el-select
                  v-model="detail.lotteryId"
                  filterable
                  placeholder="请选择抽奖"
                  clearable
                  size="small"
                  class="margin-left-xs"
                  style="width:100%"
                >
                  <el-option
                    v-for="dict in detail.lotteryList"
                    :key="dict.id"
                    :label="dict.lotteryName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="跳转方式" :prop="'details.' + index + '.clickType'"
                  :rules="[{ required: true, message: '点击方式不能为空', trigger: 'blur'}]">
                  <el-select
                    v-model="detail.clickType"
                    filterable
                    placeholder="请选择跳转方式"
                    clearable
                    size="small"
                    class="margin-left-xs"
                    style="width:100%"
                    @change="handleClickTypeChange(detail)"
                  >
                    <el-option
                      v-for="dict in topicDetailClickTypeList"
                      :key="dict.value"
                      :label="dict.text"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" :prop="'details.' + index + '.sort'"
                  :rules="[{ required: true, message: '排序不能为空', trigger: 'blur'}]">
                  <el-input-number
                    placeholder="请输入排序"
                    v-model="detail.sort"
                    controls-position="right"
                    :min="0"
                    style="width:100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <template v-if="detail.clickType && detail.clickType != topicDetailClickTypeEnum.none">
              <el-tabs type="border-card" style="margin:0px 0px 30px 0px">
                <el-tab-pane label="跳转设置">
                  <el-row v-for="(position, positionIndex) in detail.positions" :key="positionIndex" 
                          :class="{'border-buttom': detail.clickType == topicDetailClickTypeEnum.part}"
                          style="margin-top:20px">
                    <el-row v-if="detail.clickType == topicDetailClickTypeEnum.part">
                      <el-row style="margin:0px 0px 20px 0px;text-align: right;" v-if="positionIndex > 0">
                        <el-link :underline="false" type="danger" @click="handlePositionDel(detail, position)">
                          <span style="font-size:12px">移除</span>
                        </el-link>
                      </el-row>

                      <el-col :span="6">
                        <el-form-item label="X坐标" :prop="'details.' + index + '.positions.' + positionIndex + '.leftX'"
                          :rules="[{ required: true, message: 'X坐标不能为空', trigger: 'blur'}]">
                          <el-input v-model="position.leftX" ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="Y坐标" :prop="'details.' + index + '.positions.' + positionIndex + '.leftY'"
                          :rules="[{ required: true, message: 'Y坐标不能为空', trigger: 'blur'}]">
                          <el-input v-model="position.leftY"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="宽度" :prop="'details.' + index + '.positions.' + positionIndex + '.btnWidth'"
                          :rules="[{ required: true, message: 'Y坐标不能为空', trigger: 'blur'}]">
                          <el-input v-model="position.btnWidth"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="高度" :prop="'details.' + index + '.positions.' + positionIndex + '.btnHeight'"
                          :rules="[{ required: true, message: 'Y坐标不能为空', trigger: 'blur'}]">
                          <el-input v-model="position.btnHeight"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row >
                      <el-form-item label="跳转位置" :prop="'details.' + index + '.positions.' + positionIndex + '.navType'"
                        :rules="[{ required: true, message: '跳转位置不能为空', trigger: 'blur'}]">
                        <el-select
                          v-model="position.navType"
                          filterable
                          placeholder="请选择跳转位置"
                          clearable
                          size="small"
                          class="margin-left-xs"
                          style="width:100%"
                          @change="handleNavTypeChange(position)"
                        >
                          <el-option
                            v-for="dict in navTypeList"
                            :key="dict.value"
                            :label="dict.text"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-row>

                    <template v-if="position.navType">
                      <el-row v-if="position.navType == navTypeEnum.sku">
                        <el-col :span="12">
                          <el-form-item label="商品" :prop="'details.' + index + '.positions.' + positionIndex + '.spuId'"
                            :rules="[{ required: true, message: '商品不能为空', trigger: 'blur'}]">
                            <el-select
                              v-model="position.spuId"
                              filterable
                              placeholder="请选择商品"
                              clearable
                              size="small"
                              class="margin-left-xs"
                              style="width:100%"
                              @change="handleSpuChange(position)"
                            >
                              <el-option
                                v-for="dict in position.goodsSpuList"
                                :key="dict.id"
                                :label="dict.spuTitle"
                                :value="dict.id"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="商品sku" :prop="'details.' + index + '.positions.' + positionIndex + '.skuId'"
                            :rules="[{ required: true, message: '商品sku不能为空', trigger: 'blur'}]">
                            <el-select
                              v-model="position.skuId"
                              filterable
                              placeholder="请选择商品sku"
                              clearable
                              size="small"
                              class="margin-left-xs"
                              style="width:100%"
                            >
                              <el-option
                                v-for="dict in position.goodsSkuList"
                                :key="dict.id"
                                :label="dict.skuName"
                                :value="dict.id"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row v-if="position.navType == navTypeEnum.topicPage">
                        <el-form-item label="专题页" :prop="'details.' + index + '.positions.' + positionIndex + '.targetTopicPageId'"
                          :rules="[{ required: true, message: '专题页不能为空', trigger: 'blur'}]">
                          <el-select
                            v-model="position.targetTopicPageId"
                            filterable
                            placeholder="请选择专题页"
                            clearable
                            size="small"
                            class="margin-left-xs"
                            style="width:100%"
                          >
                            <el-option
                              v-for="dict in position.topicPageList"
                              :key="dict.id"
                              :label="dict.topicName"
                              :value="dict.id"
                            />
                          </el-select>
                        </el-form-item>
                      </el-row>
                    </template>
                  </el-row>

                  <div style="margin-top:20px" v-if="detail.clickType == topicDetailClickTypeEnum.part">
                    <el-row type="flex" justify="center">
                      <el-button
                        icon="el-icon-plus"
                        type="primary"
                        @click="handleAddDetailPosition(detail)"
                        >添加跳转设置</el-button>
                    </el-row>
                  </div>
                  
                </el-tab-pane>
              </el-tabs>
            </template>
          </el-row>

          <div style="margin-top:20px">
            <el-row type="flex" justify="center">
              <el-button
                icon="el-icon-plus"
                type="primary"
                @click="handleAddTopicPageDetail()"
                >添加</el-button>
            </el-row>
          </div>

        </el-form>
      </div>

      <div class="dialog__footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
      
    </el-drawer>
    
  </div>
</template>

<script>
import {topicDetailTypeEnum, topicDetailClickTypeEnum, navTypeEnum, navTypeList} from '@/const/const';
import ImageUploadSingle from '@/components/imageUploadSingle';
import {getGoodsSpuList} from '@/api/shop_goods/spu';
import {getGoodsSkuBySpuId} from '@/api/shop_goods/sku';
import {getLotteryList} from '@/api/shop_operate/lottery'
import {getTopicPageList, batchSave, getTopicPageDetailById} from '@/api/shop_operate/topic/topic';

export default{
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return{
      // 专题页详情类型
      topicDetailTypeEnum,
      // 点击类型
      topicDetailClickTypeEnum,
      // 跳转类型
      navTypeEnum,
      // 跳转类型列表
      navTypeList,

      dataForm:{
        id:null,
        details:[]
      },
      dataRule:{},
      loading:false,

      topicDetailTypeList:[{
        value:topicDetailTypeEnum.image,
        text:'图片类型'
      },{
        value:topicDetailTypeEnum.lottery,
        text:'抽奖类型'
      }],

      topicDetailClickTypeList:[{
        value:topicDetailClickTypeEnum.none,
        text:'无跳转'
      },{
        value:topicDetailClickTypeEnum.full,
        text:'全图片跳转'
      },{
        value:topicDetailClickTypeEnum.part,
        text:'部分图片跳转'
      }],

      // 商品列表
      goodsSpuList:[],
      // 抽奖列表
      lotteryList:[],
      // 专题页列表
      topicPageList:[]
    }
  },
  components: {
    ImageUploadSingle
  },
  methods:{

    init(id){
      this.dataForm.id = id
      // 获取商品列表
      this.getGoodsSpuList()
      // 获取抽奖信息
      this.getLotteryList()
      // 获取专题页信息
      this.getTopicPageList();

      if(id){
        // 获取详情
        getTopicPageDetailById(id).then(res=>{
          let data = res.data.data

          let dataForm = {
            id:data.id,
            details:data.details
          }
          
          if(dataForm.details.length > 0){
            dataForm.details.forEach(detail=>{
              if(detail.type == topicDetailTypeEnum.lottery){
                // 抽奖类型的场合
                detail.lotteryList = this.lotteryList
              }
              if(detail.imageUrl){
                // 解析图片路径
                let arr = JSON.parse(detail.imageUrl)
                if(arr.length > 0){
                  detail.imageUrl = arr[0]
                }
              }

              detail.positions.forEach(position=>{
                if(position.navType == navTypeEnum.sku){
                  // 商品跳转的场合
                  position.goodsSpuList = this.goodsSpuList
                  this.getGoodsSkuBySpuId(position)
                } else if(position.navType == navTypeEnum.topicPage){
                  // 专题页跳转的场合
                  position.topicPageList = this.topicPageList
                }
              })
            })
            this.dataForm = dataForm
          } else {
            this.handleAddTopicPageDetail()
          }
        })
      }      
    },

    /**
     * 类型选择
     */
    handleTypeChange(item){
      item.imageUrl = null
      item.lotteryId = null
      if(item.type == topicDetailTypeEnum.lottery){
        // 抽奖的场合
        item.lotteryList = this.lotteryList
      }
    },

    /**
     * 跳转方式选择
     */
    handleClickTypeChange(detail){
      if(detail.clickType == topicDetailClickTypeEnum.full || detail.clickType == topicDetailClickTypeEnum.part){
        detail.positions = [{
          leftX:null,
          leftY:null,
          btnWidth:null,
          btnHeight:null,
          navType:null,
          spuId:null,
          skuId:null,
          targetTopicPageId:null,
        }]
      } else {
        detail.positions = []
      }
    },

    /**
     * 
     */
    handleAddDetailPosition(detail){
      detail.positions.push({
        leftX:null,
        leftY:null,
        btnWidth:null,
        btnHeight:null,
        navType:null,
        spuId:null,
        skuId:null,
        targetTopicPageId:null,
      })
    },

    /**
     * 跳转位置选择
     */
    handleNavTypeChange(position){
      position.spuId = null
      position.skuId = null
      position.targetTopicPageId = null
      if(position.navType == navTypeEnum.sku){
        position.goodsSpuList = this.goodsSpuList
      } else if(position.navType == navTypeEnum.topicPage){
        position.topicPageList = this.topicPageList
      } else {
        position.goodsSpuList = []
        position.goodsSkuList = []
        position.topicPageList = []
      }
    },

    /**
     * 商品选择
     */
    handleSpuChange(position){
      position.skuId = null
      this.getGoodsSkuBySpuId(position)
    },

    /**
     * 获取所有的商品spu
     */
     getGoodsSpuList(){
      getGoodsSpuList().then(res=>{
        this.goodsSpuList = res.data.data
      })
    },

    /**
     * 获取抽奖信息
     */
    getLotteryList(){
      getLotteryList().then(res=>{
        this.lotteryList = res.data.data
      })
    },

    /**
     * 获取专题页信息
     */
    getTopicPageList(){
      getTopicPageList().then(res=>{
        this.topicPageList = res.data.data
      })
    },

    /**
     * 根据spuId获取sku列表
     */
    getGoodsSkuBySpuId(position){
      if(position.spuId){
        this.loading = true
        getGoodsSkuBySpuId({spuId:position.spuId}).then(res=>{
          this.loading = false
          position.goodsSkuList = res.data.data
        })
      } else {
        position.goodsSkuList = []
      }
    },

    /**
     * 提交
     */
    handleSubmit(){
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          let submitData = {
            id: this.dataForm.id,
            details: JSON.parse(JSON.stringify(this.dataForm.details))
          }

          submitData.details.forEach(detail=>{
            if(detail.imageUrl){
              detail.imageUrl = detail.imageUrl.materialId
            }
            delete detail.lotteryList
            detail.positions.forEach(position=>{
              delete position.goodsSpuList
              delete position.goodsSkuList
              delete position.topicPageList
            })
          })

          console.log(submitData)

          // 修改
          batchSave(submitData).then((data) => {
            this.$notify.success("操作成功");
            this.$emit("refreshDataList");
            this.closeDialog()
          }).catch(() => {
            this.canSubmit = true;
          });
        }
      })
    },

    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * 添加抽奖详情
     */
     handleAddTopicPageDetail(){
      this.dataForm.details.push({
        type:null,
        imageUrl:null,
        lotteryId:null,
        clickType:null,
        positions:[{
          leftX:'',
          leftY:'',
          btnWidth:'',
          btnHeight:'',
          navType:null,
          spuId:null,
          skuId:null,
          navTopicPageId:null,
        }],
        
        sort:0
      })
    },

    /**
     * 删除
     */
     handleDel(item){
      for(let i = 0; i < this.dataForm.details.length; i++){
        if(JSON.stringify(this.dataForm.details[i]) == JSON.stringify(item)){
          this.dataForm.details.splice(i,1)
          break;
        }
      }
    },

    /**
     * 删除坐标项
     */
    handlePositionDel(detail ,position){
      for(let i = 0; i < detail.positions.length; i++){
        if(JSON.stringify(detail.positions[i]) == JSON.stringify(position)){
          detail.positions.splice(i,1)
          break;
        }
      }
    }


  }
}
</script>


<style scoped>

.header-icon{
  font-size: 16px;
  margin-right: 10px;
}

.title-size{
  font-size: 16px;
}

.dialog__footer {
  display: block;
  padding: 10px 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-top: 1px solid #f0f0f0;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: #fff;
  text-align: right;
}

.border-buttom{
  border-bottom: #cccccc solid 1px;
}

.required-table-column{
  margin-right:2px; color:#FF0000
}

/* .el-form-item{
    margin-bottom: 0px;
} */
</style>